/**
 *
 * @param min 区间最小值
 * @param max 区间最大值
 * @returns 返回区间中随机一个值
 */
export function getRangeValue(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

/**
 * @function 格式化参数
 * @param paramsObject {Object<any>} 需要格式化的params
 */
export function serializeParams(paramsObject) {
  const params = new URLSearchParams();

  Object.entries(paramsObject).forEach(([key, value]: [string, any]) => {
    if (Array.isArray(value)) {
      value.forEach((item) => params.append(key, item));
    } else {
      params.append(key, value);
    }
  });

  return params.toString();
}

/**
 * 生成一个用不重复的ID
 * @param { Number } randomLength
 */
export function getUuiD(randomLength = 10) {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    const r = (Math.random() * randomLength) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(randomLength);
  });
}

/**
 *
 * @param targetValue {string} 需要复制的值
 */
export function copyText(targetValue: string) {
  const textInput = document.createElement('input');
  textInput.value = targetValue;
  document.body.appendChild(textInput);
  textInput.select();
  document.execCommand('copy');
  document.body.removeChild(textInput);
}

/**
 * @function replaceToHidden
 * @param originString {string} 需要隐藏的字符串
 * @param startRetain {number} 从哪个位置开始
 * @param endRetain {number} 从后面哪个位置开始
 * @param subString 填充的符号
 */
export function replaceToHidden(originString, startRetain = 1, endRetain = 1, subString = '*') {
  if (!originString || typeof originString !== 'string' || typeof startRetain !== 'number' || typeof endRetain !== 'number' || typeof subString !== 'string') {
    console.error('请检查传入的参数是否正确 !');
    return '';
  }
  const reg = new RegExp(`(?<=.{${startRetain}}).{1}(?=.{${endRetain}})`, 'g');
  return originString.replace(reg, subString);
}

/**
 * @function preload 图片预加载
 * @param imgs {string[]}
 * @return Promise<void>
 */
export const preload = (imgs) => {
  return new Promise((resolve, reject) => {
    if (!imgs.length) {
      reject(false);
    }

    const len = imgs.length;
    let count = 0;

    const load = (src) => {
      const img = new Image();
      const checkIfFinished = () => {
        count++;
        if (count === len) {
          resolve(true);
        }
      };

      img.onload = checkIfFinished;
      img.onerror = checkIfFinished;

      img.src = src;
    };
    imgs.forEach(load);
  });
};

/**
 * @function 通过数组内某个字段出现的次数
 * @param array 需要统计的数组
 * @param generateKey 自定义统计的参数
 * @example age => age > 10
 */
export function countBy(array, generateKey) {
  const result = {};
  for (const u of array) {
    const key = generateKey(u);
    if (result[key]) {
      result[key]++;
    } else {
      result[key] = 1;
    }
  }
  return result;
}
